<?php
namespace Home\Model;
use Think\Model;
class CartModel extends Model{
	//从登录用户购物车获取商品
	public function getList($userId){
		$sql = M("cart")->join("left join goods ON goods.GoodId = cart.goods_GoodId")->where("cart.goods_Color=goods.Color and cart.goods_Version=goods.Version and cart.user_UserId=$userId")->select();
		return $sql;
	}
	
	//添加购物车
	public function addCart($userId,$gid,$color,$version,$num){
		$where['user_UserId']=$userId;
		$where['goods_GoodId']=$gid;
		$where['goods_Color']=$color;
		$where['goods_Version']=$version;
		//判断该商品是否已经存在
		$rst = $this->where($where)->field('Count')->find();
		if ($rst) { //存在添加数量
			$num += $rst['Count'];
			return $this->where($where)->save(array('Count'=>$num));
		}
		//不存在
		//var_dump($this->find());	
		return $this->add(array(
		       'user_UserId'=>$userId,'goods_GoodId'=>$gid,'goods_Color'=>$color,'goods_Version'=>$version,'Count'=>$num,
		));
	}
	
	//添加购买成功的订单
	public function getOrderdetail($userId){
		//实例化数据表 -- 建立关联
		$goods = C('DB_PREFIX').'goods';
		$cart = C('DB_PREFIX').'cart';
		//执行SQL语句
		$sql = "select g.GoodName,g.Version,g.Color,g.Price,c.Count from $cart c join $goods g on
		        g.GoodId = c.goods_GoodId where c.user_UserId=$userId";
		return $this->query($sql);
	}
	
	//判断商品buy是否为1 显示已购买显示出订单
	public function getbuygoods($userId){
		//实例化数据表 -- 建立关联
		$goods = C('DB_PREFIX').'goods';
		$cart = C('DB_PREFIX').'cart';
		//执行SQL语句
		$sql = "select g.GoodId,g.GoodName from $cart c join $goods g on
		        g.GoodId = c.goods_GoodId where c.user_UserId=$userId and c.Buy='1' ";
		//var_dump($col);
		return $this->query($sql);
	}
}
?>